//
//  PopTopOrBottomOutFatherView.swift
//  ZHFToolBox
//
//  Created by 张海峰 on 2018/5/10.
//  Copyright © 2018年 张海峰. All rights reserved.
//
/*该demo是和大家分享一下，在项目中自定义各种弹框的思路，用来支撑自己项目的使用，无论什么样的弹框，只要有思路，
相信大家都能完美实现。感觉我这个demo对你有启发或者帮助，不妨给个星星吧
    https://github.com/FighterLightning/ZHFToolBox.git
https://www.jianshu.com/p/88420bc4d32d
 */
import UIKit

class PopTopOrBottomOutView: UIView {
    var cancelBtn :UIButton = UIButton()
    var outerImage:UIImageView = UIImageView()
    var dkeStr : String = ""
    var whiteView :UIView = UIView()
    //背景区域的颜色和透明度
    var backgroundColor1:UIColor  = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.4)
    var topOrBottomViewStartFrame = CGRect.init(x: 25, y: kScreenHeight, width: kScreenWidth, height: 500)
    //初始化视图
    func initPopBackGroundView() -> UIView {
        self.frame = CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
        self.backgroundColor = backgroundColor1
        self.isHidden = true
        //为落下的视图添加背景图
        let innerImage:UIImageView = UIImageView.init(frame: CGRect.init(x: 0, y: kScreenHeight - 210, width: kScreenWidth, height: 210))
        
        innerImage.image = UIImage.init(named: "inner_layerImage")
        self.addSubview(innerImage)
        
        outerImage = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        outerImage.isHidden = true
        outerImage.image = UIImage.init(named: "outer_layerImage")
        self.addSubview(outerImage)
        return self
    }
    //为白色视图添加子视图
    func addWhiteViewSubView() {
        
        let imageView: UIImageView = UIImageView.init(frame: CGRect.init(x: 0, y: 0, width: whiteView.frame.size.width, height: whiteView.frame.size.height))
        imageView.layer.masksToBounds = true
        imageView.contentMode = UIViewContentMode.scaleAspectFill
        imageView.image = UIImage.init(named: "bmw_image")
        imageView.isUserInteractionEnabled = true
        imageView.backgroundColor = UIColor("#2B3359")
        whiteView.addSubview(imageView)
        let titleLabel: UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 15, width: whiteView.frame.size.width, height: 16))
        titleLabel.textColor = UIColor.white
        titleLabel.font = UIFont.systemFont(ofSize: 15)
        titleLabel.text = XALanguageManager.getString(key: "成功")
        titleLabel.textAlignment = .center
        imageView.addSubview(titleLabel)
        
        let topphoto = UIImageView()
        topphoto.layer.cornerRadius = 23;
        imageView.addSubview(topphoto)
        topphoto.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.size.equalTo(CGSize(width: 64, height: 64))
            make.centerY.equalTo(self)
        }
        
        topphoto.sd_setImage(with: NSURL.init(string: "")! as URL, placeholderImage: UIImage.init(named: "成功-2@2x"), options: [], progress: nil, completed:nil)
        
        
        
        let contentLabel: UILabel = UILabel.init(frame: CGRect.init(x: 20, y: 200 , width: whiteView.frame.size.width - 40, height: 16))
        contentLabel.textColor = UIColor("#307BF6")
        contentLabel.font = UIFont.systemFont(ofSize: 15)
        contentLabel.numberOfLines = 0
        contentLabel.textAlignment = NSTextAlignment.center
        contentLabel.text = String(format: "%@ %@", XALanguageManager.getString(key: "Success"),dkeStr)
        imageView.addSubview(contentLabel)
        
        
        
        let codeImage = UIImageView()
        codeImage.isHidden = true
        codeImage.layer.cornerRadius = 23;
        imageView.addSubview(codeImage)
        codeImage.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: 200, height: 200))
            make.top.equalTo(160)
        }
        let url = "https://www.jianshu.com/u/01b7a2dd26e8oioiio";
        //你的头像（可以为nil）
        let headerImage = UIImage(named: "")
        //生成图片并且显示
        codeImage.image = setupQRCodeImage(url, image: headerImage)
        
        let Bottombutton = UIButton()
        Bottombutton.layer.cornerRadius = 20;
        imageView.addSubview(Bottombutton)
        Bottombutton.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: kScreenWidth - 50, height: 44))
            make.top.equalTo(codeImage.snp.bottom).offset(15)
        }
        Bottombutton.backgroundColor = UIColor("#297EFB")
        Bottombutton.setTitle(XALanguageManager.getString(key: "Confirm"), for: .normal)
        Bottombutton.addTarget(self, action: #selector(PopTopOrBottomOutView.backPop), for: .touchUpInside)
        
        Bottombutton.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        
        
        let bottomLabel = UILabel()
//        bottomLabel.layer.cornerRadius = 23;
        imageView.addSubview(bottomLabel)
        bottomLabel.font = UIFont.systemFont(ofSize: 13)
        bottomLabel.textAlignment = .center
        bottomLabel.adjustsFontSizeToFitWidth = true
        bottomLabel.snp.makeConstraints { (make) in
            make.centerX.equalTo(imageView)
            make.size.equalTo(CGSize(width: kScreenWidth - 20, height: 17))
            make.top.equalTo(Bottombutton.snp.bottom).offset(15)
        }
        bottomLabel.text = XALanguageManager.getString(key: "")
        bottomLabel.textColor = UIColor("#297EFB")
        //
        
        
        
        
        let cancelButton = UIButton(frame: CGRect(x: 15, y: 15, width: 15, height: 15))
        cancelButton.setImage(UIImage.init(named: "关  闭@2x"), for: .normal)
        imageView.addSubview(cancelButton)
         cancelButton.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        
    }
    
    @objc func backPop() {
        let theViewControllerYouSee = UIViewController.currentViewController()
        theViewControllerYouSee?.navigationController?.popToRootViewController(animated: true)
    }
    
    
    
    
    
    func addAnimateFromBottom() {
    UIApplication.shared.keyWindow?.addSubview(self.initPopBackGroundView())
        self.isHidden = false
        self.cancelBtn.isHidden = true
        
        self.cancelBtn = UIButton.init(type: UIButtonType.custom)
        self.cancelBtn.frame = CGRect.init(x:0, y:0, width: kScreenWidth, height: kScreenHeight)
        self.cancelBtn.tag = 1
        self.cancelBtn.setImage(UIImage.init(named: "cancel_white"), for: UIControlState.normal)
        self.cancelBtn.addTarget(self, action: #selector(self.cancelBtnClickBottom), for: UIControlEvents.touchUpInside)
        self.addSubview(self.cancelBtn)
        
        
        self.whiteView.frame = topOrBottomViewStartFrame
        self.whiteView.backgroundColor = ZHFColor.zhf_colorAlpha(withHex: 0xffffff, alpha: 0)
        self.addSubview(self.whiteView)
        addWhiteViewSubView()
        
        
        UIView.animate(withDuration:0.25, animations: {
            self.whiteView.frame.origin.y = kScreenHeight - 480
            self.bringSubview(toFront:self.outerImage)
        }) { (_) in
            UIView.animate(withDuration: 0.1, animations: {
                self.whiteView.frame.origin.y = kScreenHeight - 480
            }, completion: { (_) in
                UIView.animate(withDuration: 0.1, animations: {
                    self.whiteView.frame.origin.y = kScreenHeight - 480
                }, completion: { (_) in
                    self.cancelBtn.isHidden = false
                    
                })
            })
        }
    }
    
    @objc func cancelBtnClickTop(btn:UIButton){
        self.cancelBtn.isHidden = true
        UIView.animate(withDuration: 0.5, animations: {
             self.whiteView.frame.origin.y = -kScreenHeight
        }) { (_) in
             self.removeFromSuperview()
        }
    }
    @objc func cancelBtnClickBottom(btn:UIButton){
        self.cancelBtn.isHidden = true
        UIView.animate(withDuration: 0.5, animations: {
            self.whiteView.frame.origin.y = kScreenHeight
        }) { (_) in
            self.removeFromSuperview()
        }
    }
    func shareAction() {
        
    }
    func nextAction(){
        //next
    }
    
    
    
    
    //MARK: -传进去字符串,生成二维码图片
    func setupQRCodeImage(_ text: String, image: UIImage?) -> UIImage {
        //创建滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        filter?.setDefaults()
        //将url加入二维码
        filter?.setValue(text.data(using: String.Encoding.utf8), forKey: "inputMessage")
        //取出生成的二维码（不清晰）
        if let outputImage = filter?.outputImage {
            //生成清晰度更好的二维码
            let qrCodeImage = setupHighDefinitionUIImage(outputImage, size: 300)
            //如果有一个头像的话，将头像加入二维码中心
            if var image = image {
                //给头像加一个白色圆边（如果没有这个需求直接忽略）
                image = circleImageWithImage(image, borderWidth: 50, borderColor: UIColor.white)
                //合成图片
                let newImage = syntheticImage(qrCodeImage, iconImage: image, width: 100, height: 100)
                
                return newImage
            }
            
            return qrCodeImage
        }
        
        return UIImage()
    }
    
    //image: 二维码 iconImage:头像图片 wi@objc @objc dth: 头像的宽 height: 头像的宽
    func syntheticImage(_ image: UIImage, iconImage:UIImage, width: CGFloat, height: CGFloat) -> UIImage{
        //开启图片上下文
        UIGraphicsBeginImageContext(image.size)
        //绘制背景图片
        image.draw(in: CGRect(origin: CGPoint.zero, size: image.size))
        
        let x = (image.size.width - width) * 0.5
        let y = (image.size.height - height) * 0.5
        iconImage.draw(in: CGRect(x: x, y: y, width: width, height: height))
        //取出绘制好的图片
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回合成好的图片
        if let newImage = newImage {
            return newImage
        }
        return UIImage()
    }
    
    //MARK: - 生成高清的UIImage
    func setupHighDefinitionUIImage(_ image: CIImage, size: CGFloat) -> UIImage {
        let integral: CGRect = image.extent.integral
        let proportion: CGFloat = min(size/integral.width, size/integral.height)
        
        let width = integral.width * proportion
        let height = integral.height * proportion
        let colorSpace: CGColorSpace = CGColorSpaceCreateDeviceGray()
        let bitmapRef = CGContext(data: nil, width: Int(width), height: Int(height), bitsPerComponent: 8, bytesPerRow: 0, space: colorSpace, bitmapInfo: 0)!
        
        let context = CIContext(options: nil)
        let bitmapImage: CGImage = context.createCGImage(image, from: integral)!
        
        bitmapRef.interpolationQuality = CGInterpolationQuality.none
        bitmapRef.scaleBy(x: proportion, y: proportion);
        bitmapRef.draw(bitmapImage, in: integral);
        let image: CGImage = bitmapRef.makeImage()!
        return UIImage(cgImage: image)
    }
    
    //生成边框
    func circleImageWithImage(_ sourceImage: UIImage, borderWidth: CGFloat, borderColor: UIColor) -> UIImage {
        let imageWidth = sourceImage.size.width + 2 * borderWidth
        let imageHeight = sourceImage.size.height + 2 * borderWidth
        
        UIGraphicsBeginImageContextWithOptions(CGSize(width: imageWidth, height: imageHeight), false, 0.0)
        UIGraphicsGetCurrentContext()
        
        let radius = (sourceImage.size.width < sourceImage.size.height ? sourceImage.size.width:sourceImage.size.height) * 0.5
        let bezierPath = UIBezierPath(arcCenter: CGPoint(x: imageWidth * 0.5, y: imageHeight * 0.5), radius: radius, startAngle: 0, endAngle: .pi * 2, clockwise: true)
        bezierPath.lineWidth = borderWidth
        borderColor.setStroke()
        bezierPath.stroke()
        bezierPath.addClip()
        sourceImage.draw(in: CGRect(x: borderWidth, y: borderWidth, width: sourceImage.size.width, height: sourceImage.size.height))
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    
}




